package com.hcbd.tdwt.util;

import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Build;

import android.util.Log;


import androidx.annotation.RequiresApi;

import com.hcbd.tdwt.base.Constant;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MyAudioTrack {

    private int mFrequency;// 采样率
    private int mChannel;// 声道
    private int mSampBit;// 采样精度
    private AudioTrack mAudioTrack;
    private  boolean isPlay=false;
    public MyAudioTrack(int frequency, int channel, int sampbit) {
        this.mFrequency = frequency;
        this.mChannel = channel;
        this.mSampBit = sampbit;
    }
    public MyAudioTrack() {

    }
    /**
     * 初始化
     */
    public void init() {
        if (mAudioTrack != null) {
            release();
        }
        // 获得构建对象的最小缓冲区大小
        int minBufSize = getMinBufferSize();
        mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                mFrequency, mChannel, mSampBit, minBufSize, AudioTrack.MODE_STREAM);
        mAudioTrack.play();
    }

    /**
     * 释放资源
     */
    public void release() {
        if (mAudioTrack != null) {
            mAudioTrack.stop();
            mAudioTrack.release();
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public  void doPlay(final File audioFile, final PlayListener  playListener) {
        new Thread(){
            @Override
            public void run() {
                if(audioFile != null) {
                    Log.e("Tag8","go there");
                    //配置播放器
                    //音乐类型,扬声器播放
                    int streamType = AudioManager.STREAM_MUSIC;
                    //录音时采用的采样频率,所有播放时同样的采样频率
                    int sampleRate = 8000;
                    //单声道,和录音时设置的一样
                    int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
                    // 录音使用16bit,所有播放时同样采用该方式
                    int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
                    //流模式
                    int mode = AudioTrack.MODE_STREAM;

                    //计算最小buffer大小
                    int minBufferSize= AudioTrack.getMinBufferSize(sampleRate,channelConfig,audioFormat);

                    //构造AudioTrack  不能小于AudioTrack的最低要求，也不能小于我们每次读的大小
                    AudioTrack audioTrack=new AudioTrack(streamType,sampleRate,channelConfig,audioFormat,
                            Math.max(minBufferSize, Constant.KEY_MAX_INPUT_SIZE),mode);
                    audioTrack.setVolume(16f);
                    //从文件流读数据
                    FileInputStream inputStream = null;

                    try {
                        //循环读数据,写到播放器去播放
                        inputStream = new FileInputStream(audioFile);
                        byte[] mBuffer=new byte[2048];
                        //循环读数据,写到播放器去播放
                        int read;
                        //只要没读完,循环播放
                        isPlay=true;

                        while((read=inputStream.read(mBuffer)) > 0) {
                            Log.i("Tag8","read:"+read);
                            audioTrack.play();

                            int ret = audioTrack.write(mBuffer, 0, read);
                            Log.i("Tag8","ret ==="+ret);
                            //检查write的返回值,处理错误
                            switch(ret) {
                                case AudioTrack.ERROR_INVALID_OPERATION:
                                case AudioTrack.ERROR_BAD_VALUE:
                                case AudioManager.ERROR_DEAD_OBJECT:
                                    audioTrack.stop();
                                    isPlay=false;
                                    playListener.stop();
                                    return;
                                default:
                                    break;
                            }
                        }
                        Log.e("Tag8","播放成功。。。。");
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("Tag8","e =" +e.toString());
                        //读取失败
                        //  playFail();
                        audioTrack.stop();

                    } finally {
                        //   mIsPlaying = false;
                        Log.i("Tag8","播放完毕");
                        isPlay=false;
                        playListener.stop();
                        //关闭文件输入流
                        if(inputStream !=null){
                            //  closeStream(inputStream);
                            try {
                                inputStream.close();
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        }
                        //播放器释放
                        // resetQuietly(audioTrack);
                        audioTrack.release();
                    }
                }
            }
        }.start();
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void doPlay(File audioFile) {
        if(audioFile != null) {
            Log.i("Tag8","go there");
            //配置播放器
            //音乐类型,扬声器播放
            int streamType = AudioManager.STREAM_MUSIC;
            //录音时采用的采样频率,所有播放时同样的采样频率
            int sampleRate = 8000;
            //单声道,和录音时设置的一样
            int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
            // 录音使用16bit,所有播放时同样采用该方式
            int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
            //流模式
            int mode = AudioTrack.MODE_STREAM;

            //计算最小buffer大小
            int minBufferSize= AudioTrack.getMinBufferSize(sampleRate,channelConfig,audioFormat);

            //构造AudioTrack  不能小于AudioTrack的最低要求，也不能小于我们每次读的大小
            AudioTrack audioTrack=new AudioTrack(streamType,sampleRate,channelConfig,audioFormat,
                    Math.max(minBufferSize, Constant.KEY_MAX_INPUT_SIZE),mode);
            audioTrack.setVolume(16f);
            //从文件流读数据
            FileInputStream inputStream = null;

            try {
                //循环读数据,写到播放器去播放
                inputStream = new FileInputStream(audioFile);
                byte[] mBuffer=new byte[2048];
                //循环读数据,写到播放器去播放
                int read;
                //只要没读完,循环播放

                while((read=inputStream.read(mBuffer)) > 0) {
                    Log.i("Tag8","read:"+read);
                    audioTrack.play();

                    int ret = audioTrack.write(mBuffer, 0, read);
                    Log.i("Tag8","ret ==="+ret);
                    //检查write的返回值,处理错误
                    switch(ret) {
                        case AudioTrack.ERROR_INVALID_OPERATION:
                        case AudioTrack.ERROR_BAD_VALUE:
                        case AudioManager.ERROR_DEAD_OBJECT:
                            audioTrack.stop();
                            return;
                        default:
                            break;
                    }
                }
                Log.e("Tag8","播放成功。。。。");
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("Tag8","e =" +e.toString());
                //读取失败
                //  playFail();
                audioTrack.stop();

            } finally {
                Log.i("Tag8","播放完毕");
                //关闭文件输入流
                if(inputStream !=null){
                    //  closeStream(inputStream);
                    try {
                        inputStream.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
                //播放器释放
                // resetQuietly(audioTrack);
                audioTrack.release();
            }
        }
    }
    /**
     * 将解码后的pcm数据写入audioTrack播放
     *
     * @param data   数据
     * @param offset 偏移
     * @param length 需要播放的长度
     */
    public void playAudioTrack(byte[] data, int offset, int length) {
        if (data == null || data.length == 0) {
            return;
        }
        try {
            mAudioTrack.write(data, offset, length);
        } catch (Exception e) {
            Log.e("MyAudioTrack", "AudioTrack Exception : " + e.toString());
        }
    }

    public int getMinBufferSize() {
        return AudioTrack.getMinBufferSize(mFrequency,
                mChannel, mSampBit);
    }

    public boolean isPlay() {
        return isPlay;
    }

    public void setPlay(boolean play) {
        isPlay = play;
    }

    public interface PlayListener{
        void play();
        void stop();
    }
    private FileInputStream fileInputStream;
    public void playInModeStream(String filePath, final PlayListener  playListener) {
        //配置播放器
        //音乐类型,扬声器播放
        int streamType = AudioManager.STREAM_MUSIC;
        //录音时采用的采样频率,所有播放时同样的采样频率
        int SAMPLE_RATE_INHZ = 8000;
        //单声道,和录音时设置的一样
        int channelConfig = AudioFormat.CHANNEL_OUT_MONO;
        // 录音使用16bit,所有播放时同样采用该方式
        int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
        //流模式
        int mode = AudioTrack.MODE_STREAM;


        final int minBufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE_INHZ, channelConfig, AUDIO_FORMAT);
        mAudioTrack = new AudioTrack(
                new AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .build(),
                new AudioFormat.Builder().setSampleRate(SAMPLE_RATE_INHZ)
                        .setEncoding(AUDIO_FORMAT)
                        .setChannelMask(channelConfig)
                        .build(),
                minBufferSize,
                AudioTrack.MODE_STREAM,
                AudioManager.AUDIO_SESSION_ID_GENERATE);
        mAudioTrack.play();

        File file = new File(filePath);
        try {
            fileInputStream = new FileInputStream(file);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        byte[] tempBuffer = new byte[minBufferSize];
                        isPlay=true;
                        while (fileInputStream.available() > 0) {

                            int readCount = fileInputStream.read(tempBuffer);
                            if (readCount == AudioTrack.ERROR_INVALID_OPERATION || readCount == AudioTrack.ERROR_BAD_VALUE) {
                                continue;
                            }
                            if (readCount != 0 && readCount != -1) {
                                mAudioTrack.write(tempBuffer, 0, readCount);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        mAudioTrack.stop();
                        isPlay=false;
                        if(fileInputStream !=null){
                            try {
                                fileInputStream.close();
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        }
                        playListener.stop();
                    }
                }
            }).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
